<template>
  <continer :isNoTabs="false">
    <template slot="search">
      <QuickSearch :advForm="quickSearchForm" @QuickSearch="queryList"></QuickSearch>
    </template>
    <template slot="oprate">
      <el-button type="primary" size="mini" @click="queryList">查询</el-button>
      <el-button size="mini" @click="addBtnFun">新增</el-button>
    </template>
    <template slot="content">
      <institutionTable ref="tableRef" class="instiutionTableBox"
        :pages="tablePages"
        :instiutionTableData="tableData"
        :batchOperate="batchOperate"
        :instiutionTableHeader="tableHeader"
        @batchClick="batchClick"
        @sizeChange="sizeChange"
        @currentChange="currentChangeFun">
      </institutionTable>
      <drawer
        direction="rtl"
        class="wechatDrawer"
        :title="drawer.title"
        :drawer="drawer.isShow"
        @save="confirmFun"
        @cancelFun="cancelFun"
        @closeDraw="cancelFun">
        <template slot="column">
          <addOrEditDock ref="funDockInfo"></addOrEditDock>
        </template>
      </drawer>
    </template>
  </continer>
</template>
<script lang="ts">
import { Component, Vue, Ref } from 'vue-property-decorator'
import institutionTable from '@/common/views/institutionTable/institutionTable.vue'
import continer from '@/common/views/configCommon/ui-modules/handle-wrapper.vue'
import QuickSearch from '@/common/views/advancedSearch/QuickSearch.vue'
import drawer from '@/common/views/drawer/index.vue'
import { deepClone } from '@/utils/common'
import addOrEditDock from '@/views/config/interface/funcDocking/addOrEditDock.vue'
import { BasicModule } from '@/store/modules/config/basic'
import { CommonModule } from '@/store/modules/common'
// eslint-disable-next-line no-unused-vars
import { Form as ElForm } from 'element-ui'
interface PageObj {
  current: number
  pageSize: number
  total: number
}
interface InterStatus {
  [x: string]: any
  status: 'enable' | 'disable'
}
@Component({
  name: 'funcDocking',
  components: { institutionTable, continer, QuickSearch, addOrEditDock, drawer }
})
export default class FuncDocking extends Vue {
  @Ref() private readonly funDockInfo !: addOrEditDock
  private $confirm: any
  private $message: any

  private quickSearchForm = {
    form: {
      label: '',
      scene: []
    },
    advSearchOptions: [ // 高级搜索数据
      { label: '功能页名称', inputType: 'input', placeholder: '请输入功能页名称', name: 'label' },
      {
        label: '应用场景',
        inputType: 'select',
        clearable: true,
        multiple: true,
        defaultProp: { label: 'name', value: 'value' },
        selectData: [
          { name: '在线', value: 'chat' },
          { name: '呼入', value: 'incoming' },
          { name: '外呼', value: 'dialout' },
          { name: '咨询转移', value: 'transfer' },
          { name: '呼叫转移', value: 'consultTransfer' },
          { name: 'webcall', value: 'webcall' },
          { name: '预览外呼', value: 'previewDialout' },
          { name: '自动外呼', value: 'autoDialout' }
        ],
        name: 'scene'
      }
    ]
  }

  private statusMap = {
    enable: { name: '启用', iconClass: 'green-color V7_iconV7tubiao_dian' },
    disable: { name: '停用', iconClass: 'red-color V7_iconV7tubiao_dian' }
  }

  private batchOperate = [ // 批量操作设置
    { name: '批量启用', action: 'disable', _id: '' },
    { name: '批量停用', action: 'enable', _id: '' }
  ]

  private sceneObj = {
    chat: { name: '在线' },
    incoming: { name: '呼入' },
    dialout: { name: '外呼' },
    transfer: { name: '咨询转移' },
    consultTransfer: { name: '呼叫转移' },
    webcall: { name: 'webcall' },
    previewDialout: { name: '预览外呼' },
    autoDialout: { name: '自动外呼' }
  }

  private tableHeader: any = [ // 列表表头
    // { type: 'select' },
    { label: '名称', prop: 'label' },
    { label: '链接', prop: 'url' },
    { label: '应用场景', prop: 'sceneName' },
    { label: '状态', prop: 'isEnable', isDictionary: true, dictionary: this.statusMap, showStatusIcon: true, isSort: true },
    { label: '最后更新时间', prop: 'updateTime', isSort: true },
    { label: '最后操作人', prop: 'updateName', isSort: true, width: 145 },
    {
      label: '操作',
      width: 130,
      handlers: [
        { name: '编辑', handleFn: (scope: any) => this.editFun(scope.row) },
        { name: '停用', className: 'danger', field: 'isEnable', status: 'enable', handleFn: (scope: any) => this.handleState(scope.row) },
        { name: '启用', field: 'isEnable', status: 'disable', handleFn: (scope: any) => this.handleState(scope.row) },
        { className: 'danger', name: '删除', handleFn: (scope: any) => this.handleDel(scope.row) }
      ]
    }
  ]

  private tablePages: PageObj = { // 翻页
    current: 1,
    pageSize: 10,
    total: 0
  }

  private tableData: any = [] // 列表数据

  private drawer: any = {
    title: '新增',
    isShow: false
  }

  private queryList (addSuccess?: any) {
    if (addSuccess) { // 新增回到第一页
      this.tablePages.current = 1
    }
    const sendData = {
      page: this.tablePages.current,
      limit: this.tablePages.pageSize,
      label: this.quickSearchForm.form.label,
      scene: this.quickSearchForm.form.scene
    }
    const actionData = { url: '/base/action/general/funcPage/list', method: 'POST', data: sendData }
    BasicModule.BasicCommonAction(actionData).then(res => {
      if (res && res.success) {
        const list = res.list || []
        if (list.length === 0) {
          const page = Math.ceil(res.count / this.tablePages.pageSize)
          if (!res.count) { // 第一页且count为0是不再发请求（!res.count，以防后端没有返回count,直接死循环）
            this.tablePages.current = 1
          } else { // 删除到最后一个回到上一页
            this.tablePages.current = page
            this.queryList()
            return false
          }
        }
        list.forEach(item => {
          let sceneName = ''
          const agentObj = deepClone(CommonModule.publicCache.userListObj)[item.updateUser]
          item.updateName = agentObj ? agentObj.name : '--'
          if (item.scene && item.scene.length > 0) {
            item.scene.forEach(sceneItem => {
              sceneName += this.sceneObj[sceneItem].name + '；'
            })
          }
          item.sceneName = sceneName
        })
        this.tableData = list
        this.tablePages.total = res.count || 0
      }
    })
  }

  private addBtnFun () {
    this.drawer.isShow = '添加'
    this.drawer.isShow = true
    this.$nextTick(() => {
      this.funDockInfo.setFunDockData()
      this.funDockInfo.setParamsArr()
    })
  }

  private cancelFun () { // 关闭详情
    this.drawer.isShow = false
    this.$nextTick(() => {
      this.funDockInfo.setFunDockData()
      this.funDockInfo.setParamsArr()
    })
  }

  private confirmFun () { // 保存
    const formRef = this.funDockInfo.$refs.dockForm as ElForm
    formRef.validate(valide => {
      if (valide) {
        this.$nextTick(() => {
          const { label, url, isEnable, isToken, isParameter, _id, scene } = this.funDockInfo.dockForm
          const sendData: any = { label, url, isEnable, isToken, isParameter, scene }
          if (_id) {
            sendData._id = _id
          }
          if (isParameter) {
            sendData.parameters = this.funDockInfo.paramsArr
          }
          const actionData = { url: `/base/action/general/funcPage/${_id ? 'update' : 'save'}`, method: 'POST', data: sendData }
          BasicModule.BasicCommonAction(actionData).then(res => {
            if (res && res.success) {
              this.$message.success(`${_id ? '修改' : '添加'}功能页成功`)
              this.drawer.isShow = false
              this.queryList()
            }
          })
        })
      }
    })
  }

  private sizeChange (size: number) { // 改变页数
    this.tablePages.pageSize = size
    this.queryList()
  }

  private currentChangeFun (page: number) { // 翻页
    this.tablePages.current = page
    this.queryList()
  }

  private editFun (row: any) { // 修改
    this.drawer.isShow = '编辑'
    this.drawer.isShow = true
    this.$nextTick(() => {
      if (this.funDockInfo) {
        this.funDockInfo.setFunDockData(row)
        if (row.isParameter) {
          this.funDockInfo.setParamsArr(row.parameters)
        }
      }
    })
  }

  private handleDel (row: any) { // 删除
    this.$confirm('确定要删除该功能页吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      const actionData = { url: '/base/action/general/funcPage/delete', method: 'POST', data: { ids: [row._id] } }
      BasicModule.BasicCommonAction(actionData).then(res => {
        if (res && res.success) {
          this.$message.success('删除功能页成功')
          this.queryList()
        }
      })
    })
  }

  private batchClick (action: string, selectList: any) {
    const data: any = { isEnable: action, _id: selectList, isBatch: true }
    this.handleState(data)
  }

  private handleState (obj: InterStatus) { // 停用||启用
    const statusMap = { disable: 'enable', enable: 'disable' }
    const status = statusMap[obj.isEnable]
    const statusName = status === 'enable' ? '启用' : '停用'
    const actionData = { url: `/base/action/general/funcPage/${status}`, method: 'POST', data: { ids: [obj._id] } }
    this.$confirm(`确定要${obj.isBatch ? '批量' : ''}${statusName}${obj.isBatch ? '' : '该'}功能页吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      BasicModule.BasicCommonAction(actionData).then((res: any) => {
        if (res && res.success) {
          this.$message.success('变更功能页状态成功')
          this.queryList()
        }
      })
    })
  }

  private mounted () {
    this.queryList()
  }
}
</script>
<style lang="stylus" scoped>
@import '~@/common/style/common.styl'
  .funcDocking
    border 1px solid $border-main
    padding 16px
    border-radius 10px
    height 100%
    overflow auto
    box-shadow 0px 0px 4px 0px #e0e6f0, 0px 1px 4px 0px #e0e6f0
    box-sizing border-box
    margin 0 2px 2px 0
    height calc(100% - 40px)
</style>
